package com.tanhua.server.service;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.CharsetUtil;
import cn.hutool.core.util.StrUtil;
import lombok.Getter;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.io.File;

/**
 * 用于读取RSA的公钥和私钥文件，如果文件不存在，就需要生成公钥和私钥文件
 */
@Service
@Getter
public class RSAService2 {

    private String publicKeyStr;

    @Value("${tanhua.rsa.dir}")
    private String rsaFileDir;

    @PostConstruct
    public void init() {
        //读取公钥
        String filePath = rsaFileDir + File.separator + "rsa.pub";
        File publicKeyFile = new File(filePath);
        if (publicKeyFile.exists()) {
            this.publicKeyStr = FileUtil.readString(publicKeyFile, CharsetUtil.CHARSET_UTF_8);
        }

        if (StrUtil.isEmpty(this.publicKeyStr)) {
            //如果读取不到公钥，不能让Server系统启动的
            throw new RuntimeException(StrUtil.format("读取公钥文件失败，请检查文件是否存在，filePath = {}", filePath));
        }

    }

}
